﻿#region References
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using System.Windows.Forms;
using System.Security.Cryptography;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using System.Data;
using CdcSoftware.Pivotal.Engine.Types.Database;
using CdcSoftware.Pivotal.Engine.Types.MailMerges;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Types.DataTemplates;
#endregion

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Staff_Login : FormClientTask
    {
        #region Private Variables.
        private System.Windows.Forms.TextBox txtCurrentPassword, txtNewPassword, txtConfirmPassword;
        private System.Windows.Forms.Button btnOk, btnCancel;
        private System.Windows.Forms.Label lblCurrentPassword, lblNewPassword, lblConfirmPassword;

        private Form popupChangePassword = null;
        private Form popupAuthorization = null;
        private bool changePassword = false;
        private bool clockOut = false;
        private DataRow[] loggedInStaff = null;
        private bool autoStoreLogout = false;
        private Id autoLogoutId = null;
        private Id autoLogoutStoreId = null;
        string autoLogoutRole = string.Empty;

        #endregion

        /// <summary>
        /// This event fires on exit of staff code field. On exit check the staff code and the fill in the corresponding staff id. If none found, then prompt the user.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-24      DS          Initial version for Retail.
        /// </history>
        public virtual void OnExitStaffCode(object sender, EventArgs args)
        {
            try
            {
                if (Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Code"]) || this.PrimaryDataRow["Login_Staff_Code"] == null)
                {
                    this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
                    EnableDisableButtons();
                    return;
                }

                DataTable staff = Globals.GetDataTable("RE_Active Staff with Staff Code?", new object[] { this.PrimaryDataRow["Login_Staff_Code"].ToString() },
                    new string[] { "RE_Staff_Id" });
                if (staff != null && staff.Rows.Count > 0)
                    this.PrimaryDataRow["Login_Staff_Id"] = staff.Rows[0]["RE_Staff_Id"];
                else
                {
                    PivotalMessageBox.Show("No Staff found for the code entered: " + this.PrimaryDataRow["Login_Staff_Code"].ToString() + "\r\nPlease enter a valid code.",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
                    this.PrimaryDataRow["Login_Staff_Code"] = DBNull.Value;
                }

                if (!this.ExitRole(TypeConvert.ToString(this.PrimaryDataRow["Login_Role"])))
                    this.PrimaryDataRow["Login_Role"] = DBNull.Value;

                EnableDisableButtons();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Staff_Code move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.10.1     2012-03-26      NN          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterStaffCode(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.FormControl.GetControlByDataName("Login_Role").Focus();
                    if (Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]))
                        this.FormControl.GetControlByDataName("Login_Staff_Code").Focus();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field Role move to the next field.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.10.1     2012-03-26      NN          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterRole(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByName("PivBtnClockIn").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        ///// <summary>
        ///// Avoid the save form dialog thrown by the system.
        ///// </summary>
        //public override void OnFormClosing()
        //{
        //    base.OnFormClosing();
        //    this.FormView.Dirty = false;
        //}

        /// <summary>
        /// Enable/Disable the buttons Clock-In and Clock-Out.
        /// </summary>
        private void EnableDisableButtons()
        {
            if (!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"])) //BR:Issue fix #4 // && !Convert.IsDBNull(this.PrimaryDataRow["Login_Role"]))
            {
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = true;
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = true;
                this.FormControl.GetControlByDataName("Login_Role").Focus();
            }
            else
            {
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = false;
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = false;
                this.FormControl.GetControlByDataName("Login_Staff_Code").Focus();
            }
        }

        /// <summary>
        /// On exit of Role, enable the clock-in clock-out buttons.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-24      DS          Initial version for Retail.
        /// </history>
        public virtual void OnExitRole(object sender, EventArgs args)
        {
            try
            {
                CdcSoftware.Pivotal.Engine.UI.Forms.PivotalDropDown pdd = (PivotalDropDown)sender;
                if (!this.ExitRole(pdd.Text))
                    this.PrimaryDataRow["Login_Role"] = DBNull.Value;

                EnableDisableButtons();

                if(!Convert.IsDBNull(this.PrimaryDataRow["Login_Role"]))
                    this.FormControl.GetControlByName("PivBtnClockIn").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On click of Clock-In button.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-24      DS          Initial version for Retail.
        /// </history>
        public virtual void OnClickClockIn(object sender, EventArgs args)
        {
            clockOut = false;
            loggedInStaff = null;
            try
            {
                if (!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Login_Role"]) &&
                    !Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                {
                    DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today", null, new string[] { "RE_Staff_Login_Id", "Staff_Id", "Staff_Code", "Out_Time", "Store_Id", "Role" });

                    //Check in the staff login secondary for the day, if the user is already logged in (row exists for the staff where out time is null) (all records across all stores)
                    //int count = (from DataRow drStaffLogin in staffLogin.Rows
                    //             where drStaffLogin["Staff_Code"].ToString() == this.PrimaryDataRow["Login_Staff_Code"].ToString() && Convert.IsDBNull(drStaffLogin["Out_Time"])
                    //             select drStaffLogin).Count();

                    int count = staffLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]).ToString() == Id.Create(this.PrimaryDataRow["Login_Staff_Id"]).ToString()
                        && Convert.IsDBNull(a["Out_Time"]));

                    if (count > 0)
                    {
                        if (count > 1)
                        {
                            PivotalMessageBox.Show("Multiple entry exists for the user. Please contact Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        DataRow[] loggedInStaffforStore = null;
                        loggedInStaffforStore = staffLogin.AsEnumerable().Where(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                           && Convert.IsDBNull(a["Out_Time"])).ToArray();

                        if (Id.Create(this.PrimaryDataRow["Store_Id"]) != Id.Create(loggedInStaffforStore[0]["Store_Id"]))
                        {
                            string store = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Store", "Name", Id.Create(loggedInStaffforStore[0]["Store_Id"])));
                            if (PivotalMessageBox.Show("You are logged in to Store " + store + ", Do you want to logout from store " + store + " and login here?", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                            {
                                //Log out old store and login new store
                                autoStoreLogout = true;
                                autoLogoutId = Id.Create(loggedInStaffforStore[0]["RE_Staff_Login_Id"]);
                                autoLogoutStoreId = Id.Create(loggedInStaffforStore[0]["Store_Id"]);
                                autoLogoutRole = TypeConvert.ToString(loggedInStaffforStore[0]["Role"]);

                                if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["Login_Staff_Id"]))))
                                    ShowChangePasswordPopup();
                                else
                                    ShowAuthorizationPopup();
                            }
                            else
                            {
                                return;
                            }

                        }
                        else
                        {
                            //User is already logged-in.
                            PivotalMessageBox.Show("User is already logged in.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        //Check if for the selected staff, the Prompt_To_Change field is set to true.
                        if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["Login_Staff_Id"]))))
                            ShowChangePasswordPopup();
                        else
                            ShowAuthorizationPopup();
                    }
                }
                else
                {
                    if (Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                    {
                        PivotalMessageBox.Show("Create a batch for the store before logging-in.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    PivotalMessageBox.Show("Please fill all the required fields marked with '*'.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On click of Clock-Out button.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-08-24      DS          Initial version for Retail.
        /// </history>
        public virtual void OnClickClockOut(object sender, EventArgs args)
        {
            clockOut = true;
            loggedInStaff = null;
            try
            {
                DataRow[] loggedInCashier = null;
                if (!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Login_Role"]) &&
                    !Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                {
                    DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today", null, new string[] { "Staff_Id", "Staff_Code", "Out_Time", "Store_Id", "Role" });

                    loggedInStaff = staffLogin.AsEnumerable().Where(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                            && Convert.IsDBNull(a["Out_Time"])).ToArray();

                    if (loggedInStaff.Count() == 1)
                    {
                        //Check if the current role and the logged-in role are the same or not, else prompt.
                        if (!string.Equals(TypeConvert.ToString(loggedInStaff[0]["Role"]), TypeConvert.ToString(this.PrimaryDataRow["Login_Role"])))
                        {
                            PivotalMessageBox.Show("You have logged-in with a different role. Please change the role and try again.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        //Do one more check to confirm that the user is already logged-out as Cashier, otherwise prompt him to logout as Cashier first.
                        DataTable cashierLogin = Globals.GetDataTable("RE_All Cashier Logins for Today", null, new string[] { "Staff_Id", "End_Time" });

                        loggedInCashier = cashierLogin.AsEnumerable().Where(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                                && Convert.IsDBNull(a["End_Time"])).ToArray();

                        if (loggedInCashier.Count() == 1)
                        {
                            PivotalMessageBox.Show("You have logged-in as Cashier. First log out as cashier and then do a staff logout.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        //Check if for the selected staff, the Prompt_To_Change field is set to true.
                        if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["Login_Staff_Id"]))))
                            ShowChangePasswordPopup();
                        else
                            ShowAuthorizationPopup();
                    }
                    else if (loggedInStaff.Count() > 1)
                        PivotalMessageBox.Show("Multiple entry exists for the user. Please contact Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                        PivotalMessageBox.Show("No entry for the user to clock-out.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    if (Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                    {
                        PivotalMessageBox.Show("The Batch is already closed for the Day.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    PivotalMessageBox.Show("Please fill all the required fields marked with '*'.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowChangePasswordPopup()
        {
            changePassword = true;
            popupChangePassword = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.txtNewPassword = new System.Windows.Forms.TextBox();
            this.txtConfirmPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            this.lblNewPassword = new System.Windows.Forms.Label();
            this.lblConfirmPassword = new System.Windows.Forms.Label();
            popupChangePassword.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 0;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // txtNewPassword
            // 
            this.txtNewPassword.Location = new System.Drawing.Point(181, 71);
            this.txtNewPassword.Name = "txtNewPassword";
            this.txtNewPassword.Size = new System.Drawing.Size(109, 20);
            this.txtNewPassword.TabIndex = 1;
            this.txtNewPassword.UseSystemPasswordChar = true;
            // 
            // txtConfirmPassword
            // 
            this.txtConfirmPassword.Location = new System.Drawing.Point(181, 112);
            this.txtConfirmPassword.Name = "txtNewPassword";
            this.txtConfirmPassword.Size = new System.Drawing.Size(109, 20);
            this.txtConfirmPassword.TabIndex = 2;
            this.txtConfirmPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 161);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 3;
            this.btnOk.Text = "Ok";
            this.btnOk.BringToFront();
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 161);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Current Password:";
            // 
            // lblNewPassword
            // 
            this.lblNewPassword.AutoSize = true;
            this.lblNewPassword.Location = new System.Drawing.Point(43, 74);
            this.lblNewPassword.Name = "lblNewPassword";
            this.lblNewPassword.Size = new System.Drawing.Size(138, 15);
            this.lblNewPassword.TabIndex = 5;
            this.lblNewPassword.Text = "New Password:";
            // 
            // lblConfirmPassword
            // 
            this.lblConfirmPassword.AutoSize = true;
            this.lblConfirmPassword.Location = new System.Drawing.Point(43, 115);
            this.lblConfirmPassword.Name = "lblConfirmPassword";
            this.lblConfirmPassword.Size = new System.Drawing.Size(138, 15);
            this.lblConfirmPassword.TabIndex = 6;
            this.lblConfirmPassword.Text = "Confirm Password:";
            // 
            // Form1
            // 
            popupChangePassword.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupChangePassword.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupChangePassword.AcceptButton = this.btnOk;
            popupChangePassword.CancelButton = this.btnCancel;
            popupChangePassword.ClientSize = new System.Drawing.Size(348, 224);
            popupChangePassword.StartPosition = FormStartPosition.CenterScreen;
            popupChangePassword.Controls.Add(this.lblCurrentPassword);
            popupChangePassword.Controls.Add(this.lblNewPassword);
            popupChangePassword.Controls.Add(this.lblConfirmPassword);
            popupChangePassword.Controls.Add(this.btnOk);
            popupChangePassword.Controls.Add(this.btnCancel);
            popupChangePassword.Controls.Add(this.txtCurrentPassword);
            popupChangePassword.Controls.Add(this.txtNewPassword);
            popupChangePassword.Controls.Add(this.txtConfirmPassword);
            popupChangePassword.Name = "popupChangePassword";
            popupChangePassword.Text = "Change Password";
            popupChangePassword.ResumeLayout(false);
            popupChangePassword.PerformLayout();
            popupChangePassword.ShowDialog();
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowAuthorizationPopup()
        {
            changePassword = false;
            popupAuthorization = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            popupAuthorization.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 1;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 80);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 2;
            this.btnOk.Text = "Ok";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 80);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 3;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Password:";
            // 
            // Form1
            // 
            popupAuthorization.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupAuthorization.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupAuthorization.AcceptButton = this.btnOk;
            popupAuthorization.CancelButton = this.btnCancel;
            popupAuthorization.ClientSize = new System.Drawing.Size(348, 133);
            popupAuthorization.StartPosition = FormStartPosition.CenterScreen;
            popupAuthorization.Controls.Add(this.lblCurrentPassword);
            popupAuthorization.Controls.Add(this.btnOk);
            popupAuthorization.Controls.Add(this.btnCancel);
            popupAuthorization.Controls.Add(this.txtCurrentPassword);
            popupAuthorization.Name = "popupAuthorization";
            popupAuthorization.Text = "Enter Password";
            popupAuthorization.ResumeLayout(false);
            popupAuthorization.PerformLayout();
            popupAuthorization.ShowDialog();
        }

        /// <summary>
        /// Event handler for the OK click of the popup pwd challenge.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-08      DS              Initial version for Retail.                                                
        /// </history>
        private void Ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (changePassword)
                {
                    //Verify the current password is correct and the new password matches the confirm password fields.
                    //Update the new password in the staff table and clear the Prompt_To_Change field and Clock-In the staff.

                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty || txtNewPassword.Text.Trim() == string.Empty || txtConfirmPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Login_Staff_Id"])));
                    //Match the old password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //If new password and the confirm password does not match prompt the user with error.
                        if (!String.Equals(txtNewPassword.Text, txtConfirmPassword.Text))
                        {
                            PivotalMessageBox.Show("Password confirmation failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.txtNewPassword.Text = string.Empty;
                            this.txtConfirmPassword.Text = string.Empty;
                            this.txtNewPassword.Focus();
                            return;
                        }

                        //Now change the password for the Staff and set the field Prompt_To_Reset to false.
                        this.SystemClient.ExecuteServerTask("RE_Store", "SetStaffPassword", new Type[] { typeof(Id), typeof(string) },
                            new object[] { Id.Create(this.PrimaryDataRow["Login_Staff_Id"]), Globals.Encrypt(this.txtNewPassword.Text) });

                        //After successful validation and password change, close the pop-up.
                        popupChangePassword.Close();

                        if (autoStoreLogout)
                        {
                            AutoClockOutStaff();
                        }

                        //Clock-In or Clock-Out the staff.
                        if (!clockOut)
                            ClockInStaff();
                        else
                            ClockOutStaff();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Current Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                }
                else
                {
                    //Verify the current password is correct and clock in the staff.
                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Login_Staff_Id"])));
                    //Match the password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //After successful validation and password change, close the pop-up.
                        popupAuthorization.Close();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    if (autoStoreLogout)
                    {
                        AutoClockOutStaff();
                    }
                    //Clock-In or Clock-Out the staff.
                    if (!clockOut)
                        ClockInStaff();
                    else
                        ClockOutStaff();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Add a new row in the secondary staff login:
        ///•	Staff_Code = Staff Code entered above
        ///•	Staff_Id =  staff_Id retrieved above
        ///•	Store_Id =  current store
        ///•	Role =  Role selected above
        ///•	Login_Date =  Current Date
        ///•	In_Time = Current Time
        ///If the role is In Charge, update the In_Charge_Id field with the selected staff_id  for all the POS records for that store.
        ///Ensure that the staff id selected has the In_Charge flag set to true.
        ///Clear all the primary input fields.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-29      DS              Initial version for Retail.                                                
        /// </history>
        private void ClockInStaff()
        {
            this.SystemClient.ExecuteServerTask("RE_Store", "ClockInStaff", new Type[] { typeof(string), typeof(object), typeof(object), typeof(string), typeof(object) },
                new object[] { this.PrimaryDataRow["Login_Staff_Code"].ToString(), this.PrimaryDataRow["Login_Staff_Id"], this.PrimaryDataRow["Store_Id"], 
                    this.PrimaryDataRow["Login_Role"].ToString(), this.PrimaryDataRow["Login_Batch_Id"] });

            //Refresh the grid data.
            PivotalSearchResultsGrid staffLoginGrid = (PivotalSearchResultsGrid)this.FormControl.GetControlByName("StaffLoginGrid");
            staffLoginGrid.RefreshGridData();

            //Clears all the primary fields.
            ClearPrimaryFields();
        }

        /// <summary>
        /// Update the logged-in row in the secondary staff login:
        ///•	Out_Time = Current Time
        ///If the role is In Charge, update the In_Charge_Id field with the selected staff_id  for all the POS records for that store.
        ///Ensure that the staff id selected has the In_Charge flag set to true.
        ///Clear all the primary input fields.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-30      DS              Initial version for Retail.                                                
        /// </history>
        private void ClockOutStaff()
        {
            this.SystemClient.ExecuteServerTask("RE_Store", "ClockOutStaff", new Type[] { typeof(Id), typeof(object), typeof(string) },
                new object[] { Id.Create(loggedInStaff[0]["RE_Staff_Login_Id"]), this.PrimaryDataRow["Store_Id"], this.PrimaryDataRow["Login_Role"].ToString() });

            //Refresh the grid data.
            PivotalSearchResultsGrid staffLoginGrid = (PivotalSearchResultsGrid)this.FormControl.GetControlByName("StaffLoginGrid");
            staffLoginGrid.RefreshGridData();

            //Clears all the primary fields.
            ClearPrimaryFields();
        }

        private void AutoClockOutStaff()
        {
            //log out from the POS if any
            DataTable cashierLogin = Globals.GetDataTable("RE_All Cashier Logins for Today", null, new string[] { "Staff_Id", "Staff_Code", "End_Time", "Store_Id", "POS_Id" });

            DataRow[] loggedInCashier = cashierLogin.AsEnumerable().Where(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                   && Convert.IsDBNull(a["End_Time"])).ToArray();

            if (loggedInCashier.Count() == 1)
            {
                //Log out cashier before logging out Staff
                this.SystemClient.ExecuteServerTask("RE_Store", "ClockOutCashier", new Type[] { typeof(Id), typeof(object), typeof(object) },
    new object[] { Id.Create(loggedInCashier[0]["RE_Cashier_Log_Id"]), loggedInCashier[0]["Store_Id"], loggedInCashier[0]["POS_Id"] });
            }

            //log out from the Store if any
            this.SystemClient.ExecuteServerTask("RE_Store", "ClockOutStaff", new Type[] { typeof(Id), typeof(object), typeof(string) },
    new object[] { autoLogoutId, autoLogoutStoreId, autoLogoutRole });

        }

        /// <summary>
        /// Clears all the primary fields.
        /// </summary>
        /// 
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-08-29      DS              Initial version for Retail.                                                
        /// </history>
        private void ClearPrimaryFields()
        {
            //this.PrimaryDataRow["Login_Batch_Id"] = DBNull.Value;
            this.PrimaryDataRow["Login_Staff_Code"] = DBNull.Value;
            this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
            this.PrimaryDataRow["Login_Role"] = DBNull.Value;
            ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = false;
            ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = false;
        }

        /// <summary>
        /// Will be called on change of Role and StaffCode.
        /// Code moved into another function with LoginRole as parameter.
        /// This is done since event attached to this field is changed to DropDownClosed.
        /// Therefore we are passing LoginRole from sender.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2012-07-04      NN              
        /// </history>
        private bool ExitRole(string loginRole)
        {
            try
            {
                if (!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]) && loginRole != string.Empty)
                {
                    bool inCharge = TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "In_Charge", Id.Create(this.PrimaryDataRow["Login_Staff_Id"])));
                    if (!inCharge && string.Equals("In Charge", loginRole))
                    {
                        PivotalMessageBox.Show("You are not authorized to login as \"In Charge\".", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
        }
    }
}
